﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Controls;
using VAdvantage.Framework;
using VAdvantage.Classes;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Threading;
using System.Text;
using System.Data.SqlClient;
using VAdvantage.DataBase;

namespace VAdvantage.Search
{
    public class InfoCashLine : Info
    {
        #region Private Variables
        private int _cashBook;
        private int _invoice;
        Object _comboCash = "-1";
        Object _comboBank = "-1";
        private ToolTip tooltip = new ToolTip();
        //on value change of datetime pickker
        private bool _dateTimeFromCheck = false;
        private bool _dateTimeToCheck = false;
        //on Amount text change value
        private bool _AmtFromCheck = false;
        private bool _AmtToCheck = false;
        //  Static Info
        private VLabel lblName = new VLabel();
        private VLabel lblCashBook_ID = new VLabel();
        private VLabel lblInvoice_ID = new VLabel();
        private VLabel lblBankAccount_ID = new VLabel();
        private VLabel lblDateFrom = new VLabel();
        private VLabel lblDateTo = new VLabel();
        private VLabel lblAmtFrom = new VLabel();
        private VLabel lblAmtTo = new VLabel();

        private VTextBox txtName = new VTextBox();
        private VComboBox cmbCashBook_ID;
        private VTextBoxButton vInvoice_ID;
        private VComboBox cmbBankAccount_ID;
        private VCheckBox chkBAbsolute = new VCheckBox();

        private VAdvantage.Controls.VDatePicker dtpDateFrom = new VAdvantage.Controls.VDatePicker();
        private VAdvantage.Controls.VDatePicker dtpDateTo = new VAdvantage.Controls.VDatePicker();
        private VNumTextBox txtAmtFrom = new VNumTextBox();
        private VNumTextBox txtAmtTo = new VNumTextBox();


        // Array of Column Info    
        private static Info_Column[] _cashLayout = {
	  new Info_Column(" ", "cl.C_CashLine_ID", typeof(IDColumn)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "C_CashBook_ID"),
	   "(SELECT cb.Name FROM C_CashBook cb WHERE cb.C_CashBook_ID=c.C_CashBook_ID)", typeof(String)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "Name"),
	   "c.Name", typeof(String)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "StatementDate"),
	   "c.StatementDate", typeof(DateTime)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "Line"),
	   "cl.Line", typeof(int)),
	 // new Info_Column(Msg.translate(Env.getCtx(), "C_Currency_ID"),
	 //  "(SELECT ISO_Code FROM C_Currency c WHERE c.C_Currency_ID=cl.C_Currency_ID)", String.class),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "Amount"),
	   "cl.Amount",  typeof(Decimal), true, true, null),
	  //
	  new Info_Column(Msg.Translate(Envs.GetContext(), "C_Invoice_ID"),
	   "(SELECT i.DocumentNo||'_'||" + DB.TO_CHAR("c.StatementDate",DisplayType.Date,Envs.GetAD_Language(Envs.GetCtx()))
	    + "||'_'||" + DB.TO_CHAR("i.GrandTotal",DisplayType.Amount,Envs.GetAD_Language(Envs.GetContext()))
	    + " FROM C_Invoice i WHERE i.C_Invoice_ID=cl.C_Invoice_ID)", typeof(String)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "C_BankAccount_ID"),
	   "(SELECT b.Name||' '||ba.AccountNo FROM C_Bank b, C_BankAccount ba WHERE b.C_Bank_ID=ba.C_Bank_ID AND ba.C_BankAccount_ID=cl.C_BankAccount_ID)", typeof(String)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "C_Charge_ID"),
	   "(SELECT ca.Name FROM C_Charge ca WHERE ca.C_Charge_ID=cl.C_Charge_ID)", typeof(String)),
	  //
	  new Info_Column(Msg.Translate(Envs.GetContext(), "DiscountAmt"),
	   "cl.DiscountAmt",  typeof(Decimal)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "WriteOffAmt"),
	   "cl.WriteOffAmt",  typeof(Decimal)),
	  new Info_Column(Msg.Translate(Envs.GetContext(), "Description"),
	   "cl.Description", typeof(String))
	 };



        #endregion

        /// <summary>
        /// Detail Protected Contructor
        /// </summary>
        /// <param name="frame">parent frame</param>
        /// <param name="modal">modal</param>
        /// <param name="WindowNo"> window no</param>
        /// <param name="value">query value</param>
        /// <param name="multiSelection">multiple selections</param>
        /// <param name="whereClause">where clause</param>
        public InfoCashLine(Object frame, bool modal, int WindowNo, String value, bool multiSelection, String whereClause)
            : base(frame, modal, WindowNo, "cl", "C_CashLine_ID", multiSelection, whereClause)
        {
            log.Info("InfoCashLine");
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "InfoCashLine", true));
            //
            try
            {
                StatInit();
                InitInfo();
            }
            catch (Exception e)
            {
                return;
            }
            //
            int no = 0;
            base.SetStatusMsg(no.ToString() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery", true));
            if (value != null && value.Length > 0)
            {
                txtName.Text = value.ToString();
                _comboCash = cmbCashBook_ID.SelectedItem;
                ExecuteQuery();
            }
            //
            //pack();
            // Focus
            txtName.Focus();
        }


        /// <summary>
        /// Get Layout
        /// </summary>
        /// <returns>array of Column_Info</returns>
        protected override Info_Column[] GetInfoColumns()
        {
            return _cashLayout;
        }

        /// <summary>
        /// General Init
        /// </summary>
        /// <returns>true, if success</returns>
        private bool InitInfo()
        {
            //  prepare table
            StringBuilder where = new StringBuilder("cl.IsActive='Y'");
            if (_whereClause.Length > 0)
            {
                where.Append(" AND ").Append(Util.Replace(_whereClause, "C_CashLine.", "cl."));
            }
            PrepareTable("C_CashLine cl INNER JOIN C_Cash c ON (cl.C_Cash_ID=c.C_Cash_ID)",
             where.ToString(),
             "2,3,cl.Line");

            return true;
        }

        private void StatInit()
        {
            SetBusy(true);
            InfoSetting();
            lblName.Content = Msg.Translate(Envs.GetContext(), "Name");
            
            lblCashBook_ID.Content = Msg.Translate(Envs.GetContext(), "C_CashBook_ID");
            lblInvoice_ID.Content = Msg.Translate(Envs.GetContext(), "C_Invoice_ID");
            lblBankAccount_ID.Content = Msg.Translate(Envs.GetContext(), "C_BankAccount_ID");
            lblDateFrom.Content = Msg.Translate(Envs.GetContext(), "StatementDate");
            lblDateTo.Content = "-";
            lblAmtFrom.Content = Msg.Translate(Envs.GetContext(), "Amount");
            lblAmtTo.Content = "-";
            //check box1
            chkBAbsolute.Content = Msg.Translate(Envs.GetContext(), "AbsoluteAmt");
            //tooltip.SetToolTip(chkBAbsolute, Msg.Translate(Envs.GetContext(), "AbsoluteAmt"));
            chkBAbsolute.IsChecked = false;


            Lookup _value = null;
            Lookup _value1 = null;

            ThreadPool.QueueUserWorkItem(delegate
            {
                _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 5249, DisplayType.TableDir);
                _value1 = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 5354, DisplayType.Search);

                Dispatcher.BeginInvoke( delegate 
                {
                    cmbCashBook_ID = new VComboBox("C_CashBook_ID", false, false, true, _value, 120);
                    vInvoice_ID = new VTextBoxButton("C_Invoice_ID", false, false, true, DisplayType.Search, _value1);

                    Grid.SetColumn(cmbCashBook_ID, 1);
                    Grid.SetRow(cmbCashBook_ID, 0);
                    this.tablePanel.Children.Add(cmbCashBook_ID);

                    Grid.SetColumn(vInvoice_ID, 1);
                    Grid.SetRow(vInvoice_ID, 1);
                    this.tablePanel.Children.Add(vInvoice_ID);

                    SetBusy(false);
                });
            });

           


            Grid.SetColumn(lblCashBook_ID, 0);
            Grid.SetRow(lblCashBook_ID, 0);
            this.tablePanel.Children.Add(lblCashBook_ID);

           

            Grid.SetColumn(lblName, 2);
            Grid.SetRow(lblName, 0);
            this.tablePanel.Children.Add(lblName);

            Grid.SetColumn(txtName, 3);
            Grid.SetRow(txtName, 0);
            this.tablePanel.Children.Add(txtName);

            Grid.SetColumn(chkBAbsolute, 5);
            Grid.SetRow(chkBAbsolute, 0);
            this.tablePanel.Children.Add(chkBAbsolute);

            Grid.SetColumn(lblInvoice_ID, 0);
            Grid.SetRow(lblInvoice_ID, 1);
            this.tablePanel.Children.Add(lblInvoice_ID);

            

            Grid.SetColumn(lblDateFrom, 2);
            Grid.SetRow(lblDateFrom, 1);
            this.tablePanel.Children.Add(lblDateFrom);

            Grid.SetColumn(dtpDateFrom, 3);
            Grid.SetRow(dtpDateFrom, 1);
            this.tablePanel.Children.Add(dtpDateFrom);

            Grid.SetColumn(lblDateTo, 4);
            Grid.SetRow(lblDateTo, 1);
            this.tablePanel.Children.Add(lblDateTo);

            Grid.SetColumn(dtpDateTo, 5);
            Grid.SetRow(dtpDateTo, 1);
            this.tablePanel.Children.Add(dtpDateTo);

            Grid.SetColumn(lblBankAccount_ID, 0);
            Grid.SetRow(lblBankAccount_ID, 2);
            this.tablePanel.Children.Add(lblBankAccount_ID);

            Grid.SetColumn(cmbBankAccount_ID, 1);
            Grid.SetRow(cmbBankAccount_ID, 2);
            this.tablePanel.Children.Add(cmbBankAccount_ID);


            Grid.SetColumn(lblAmtFrom, 2);
            Grid.SetRow(lblAmtFrom, 2);
            this.tablePanel.Children.Add(lblAmtFrom);

            Grid.SetColumn(txtAmtFrom, 3);
            Grid.SetRow(txtAmtFrom, 2);
            this.tablePanel.Children.Add(txtAmtFrom);

            Grid.SetColumn(lblAmtTo, 4);
            Grid.SetRow(lblAmtTo, 2);
            this.tablePanel.Children.Add(lblAmtTo);

            Grid.SetColumn(txtAmtTo, 5);
            Grid.SetRow(txtAmtTo, 2);
            this.tablePanel.Children.Add(txtAmtTo);

            txtName.KeyDown += new KeyEventHandler(txtName_KeyDown);
            dtpDateFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateFrom_SelectedDateChanged);
            dtpDateTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateTo_SelectedDateChanged);
            cmbBankAccount_ID.SelectionChanged += new SelectionChangedEventHandler(cmbBankAccount_ID_SelectionChanged);
            txtAmtFrom.TextChanged += new TextChangedEventHandler(txtAmtFrom_TextChanged);
            txtAmtTo.TextChanged += new TextChangedEventHandler(txtAmtTo_TextChanged);
        }

        void txtAmtTo_TextChanged(object sender, TextChangedEventArgs e)
        {
            _AmtToCheck = true;
        }

        void txtAmtFrom_TextChanged(object sender, TextChangedEventArgs e)
        {
            _AmtFromCheck = true;
        }

        void cmbBankAccount_ID_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _comboCash = cmbCashBook_ID.SelectedItem;
        }

        void dtpDateTo_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeToCheck = true;
        }

        void dtpDateFrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeFromCheck = true;
        }

        void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            //ExecuteQuery();
            {
                Search();
            }
        }

        void Search()
        {
            ExecuteQuery();
        }

        protected override void bRefresh_Click(object sender, RoutedEventArgs e)
        {
            //base.bRefresh_Click(sender, e);
            Search();
        }

        private void InfoSetting()
        {
            RowDefinition row = new RowDefinition();
            row.Height = GridLength.Auto;// new GridLength(0, GridUnitType.Auto);
           // row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = GridLength.Auto;
           // row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = GridLength.Auto;
            //row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);


            ColumnDefinition column = new ColumnDefinition();
            column.Width = GridLength.Auto;
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width =  new GridLength(1, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);


            column = new ColumnDefinition();
            column.Width = GridLength.Auto;
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(1, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = GridLength.Auto;
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(1, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);            
        }


        string _name = "";
        object bpValue = null;
        string dateFrom = "";
        string dateTo = "";
        bool ischkBAbsolute = false;
        string amtFrom = "";
        string amtTo = "";

        /// <summary>
        /// Construct SQL Where Clause and define parameters.
        /// (setParameters needs to set parameters)
        /// Includes first AND
        /// </summary>
        /// <returns>sql</returns>
        public override String GetSQLWhere()
        {
            StringBuilder sql = new StringBuilder();

            if (_name.Length > 0)
            {
                sql.Append(" AND UPPER(c.Name) LIKE @param1");
            }
            int C_CashBook_ID = 0;
            KeyNamePair wh = null;
            if (!_comboCash.Equals("-1"))
            {
                wh = (KeyNamePair)_comboCash;
            }
            if (wh != null)
            {
                C_CashBook_ID = wh.GetKey();
            }
            if (C_CashBook_ID != -1 && C_CashBook_ID != 0)
            {
                sql.Append(" AND c.C_CashBook_ID=@param2");
            }
            //if (cmbCashBook_ID.SelectedValue.ToString() != "-1")
            //cmbCashBook_ID.SelectedItem = _comboCash;
            //if (cmbCashBook_ID.GetValue() != DBNull.Value)
            //{
            //    sql.Append(" AND c.C_CashBook_ID=@param2");
            //}
            //
            if (bpValue != null && bpValue != DBNull.Value)
            {
                sql.Append(" AND cl.C_Invoice_ID=@param3");
            }
            //
            if ((!String.IsNullOrEmpty(dateFrom)) || (!string.IsNullOrEmpty(dateTo)))
            {
                if (!_dateTimeFromCheck && _dateTimeToCheck)
                {
                    sql.Append(" AND TRUNC(c.StatementDate,'DD') <= @param6");
                }
                else if (_dateTimeFromCheck && !_dateTimeToCheck)
                {
                    sql.Append(" AND TRUNC(c.StatementDate,'DD') >= @param5");
                }
                else if (_dateTimeFromCheck && _dateTimeToCheck)
                {
                    sql.Append(" AND TRUNC(c.StatementDate,'DD') BETWEEN @param5 AND @param6");
                }
            }
            //
            if ((!String.IsNullOrEmpty(amtFrom)) || (!string.IsNullOrEmpty(amtTo)))
            {
                //this is for default text in the number text box
                if (amtFrom == "0" && amtTo == "0")
                {

                }
                else
                {
                    Decimal from = Convert.ToDecimal(txtAmtFrom.Text);
                    Decimal to = Convert.ToDecimal(txtAmtTo.Text);
                    if (ischkBAbsolute)
                    {
                        sql.Append(" AND ABS(cl.Amount)");
                    }
                    else
                    {
                        sql.Append(" AND cl.Amount");
                    }
                    //
                    if ((!_AmtFromCheck && _AmtToCheck))
                    {
                        sql.Append(" <=@param8");
                    }
                    else if ((!_AmtToCheck && _AmtFromCheck))
                    {
                        sql.Append(" >=@param7");

                    }
                    else if ((_AmtFromCheck && _AmtToCheck))
                    {
                        if (from.CompareTo(to) == 0)
                        {
                            sql.Append(" =@param7");
                        }
                        else
                        {
                            sql.Append(" BETWEEN @param7 AND @param8");
                        }
                    }
                }
            }

            log.Fine(sql.ToString());
            return sql.ToString();
        }

        /// <summary>
        /// Get SQL WHERE parameter
        /// </summary>
        /// <param name="f">field</param>
        /// <returns>sql</returns>
        private String GetSQLText(string f)
        {
            String s = f.ToUpper();
            if (!s.EndsWith("%"))
            {
                s += "%";
            }
            log.Fine("String=" + s);
            return s;
        }


        /// <summary>
        /// Set Parameters for Query.
        /// (as defined in getSQLWhere)
        /// </summary>
        /// <param name="param">statement</param>
        /// <param name="forCount">for counting records</param>
        public override void SetParameters(out SqlParameter[] param, bool forCount)
        {
            String name = GetSQLText(_name);
            Decimal grantAmtFrom = Util.GetValueOfDecimal(amtFrom);
            Decimal grantAmtTo = Util.GetValueOfDecimal(amtTo);
            int C_CashBook_ID = 0;
            KeyNamePair wh = new KeyNamePair();
            wh = (KeyNamePair)_comboCash;
            if (wh != null)
            {
                C_CashBook_ID = wh.GetKey();
            }

            //if (cmbCashBook_ID.SelectedValue.ToString()!="-1")// cmbCashBook_ID.GetValue() != null)
            if (bpValue != DBNull.Value)
            {
                _cashBook = Convert.ToInt32(bpValue);

            }
            if (bpValue != null)
            {
                _invoice = Convert.ToInt32(bpValue);

            }
            int paramcount = 0;
            if (!(name.Equals("") || name.Equals("%")))
            {
                paramcount++;
            }
            if (!(_cashBook.Equals("") || _cashBook.Equals("%") || _cashBook == 0 || C_CashBook_ID == -1))
            {
                paramcount++;
            }
            if (!(_invoice.Equals("") || _invoice.Equals("%") || _invoice == 0))
            {
                paramcount++;
            }
            //if (!(cmbBankAccount_ID.Equals("") || cmbBankAccount_ID.Equals("%")))
            //{
                // paramcount++;
            //}
            //becouse this contain default date
            if (_dateTimeFromCheck)
            {
                paramcount++;
            }
            if (_dateTimeToCheck)
            {
                paramcount++;
            }
            if (amtFrom == "0" && amtTo == "0")
            {
            }
            else
            {
                if (_AmtFromCheck)
                {
                    paramcount++;
                }
                if (_AmtToCheck)
                {
                    paramcount++;
                }
            }

            param = new SqlParameter[paramcount];
            int index = 0;
            if (name.Length > 0)
            {
                if (!name.EndsWith("%"))
                {
                    name += "%";
                }
                param[index++] = new SqlParameter("@param1", name);
            }
            if (!(_cashBook.Equals("") || _cashBook.Equals("%") || _cashBook == 0 || C_CashBook_ID == -1))
            {
                param[index++] = new SqlParameter("@param2", _cashBook);
                log.Fine("CashBook=" + _cashBook);
            }
            if (!(_invoice.Equals("") || _invoice.Equals("%") || _invoice == 0))
            {
                param[index++] = new SqlParameter("@param3", _invoice);
                log.Fine("Invoice=" + _invoice);
            }
            if (!(cmbBankAccount_ID.Equals("") || cmbBankAccount_ID.Equals("%")))
            {
                //param[index++] = new SqlParameter("@param4", Convert.ToInt32(cmbBankAccount_ID.GetValue()));
            }
            if ((dateFrom != null || dateTo != null) && (dateFrom != "" || dateTo != ""))
            {
                //	=> Date Ordered From
                if (_dateTimeFromCheck)
                {
                    param[index++] = new SqlParameter("@param5", Convert.ToDateTime(dtpDateFrom.Text));
                }
                //	=> Date Ordered TO
                if (_dateTimeToCheck)
                {
                    param[index++] = new SqlParameter("@param6", Convert.ToDateTime(dtpDateTo.Text));
                }
            }
            if (amtFrom == "0" && amtTo == "0")
            {
            }
            else
            {
                if (ischkBAbsolute)
                {
                    if (_AmtFromCheck)
                    {
                        grantAmtFrom = Math.Abs(grantAmtFrom);//.abs();
                    }
                    if (_AmtToCheck)
                    {
                        grantAmtTo = Math.Abs(grantAmtTo);//.abs();
                    }
                }
                log.Fine("Amt From=" + grantAmtFrom + ", To=" + grantAmtTo + ", Absolute=" + ischkBAbsolute);
                if ((!_AmtFromCheck && _AmtToCheck))
                {
                    param[index++] = new SqlParameter("@param8", grantAmtTo);
                }
                else if ((!_AmtToCheck && _AmtFromCheck))
                {
                    param[index++] = new SqlParameter("@param7", grantAmtFrom);

                }
                else if ((_AmtFromCheck && _AmtToCheck))
                {
                    if (grantAmtFrom.CompareTo(grantAmtTo) == 0)
                    {
                        //pstmt.setBigDecimal(index++, from);
                        param[index++] = new SqlParameter("@param7", grantAmtFrom);
                    }
                    else
                    {
                        //pstmt.setBigDecimal(index++, from);
                        //pstmt.setBigDecimal(index++, to);
                        param[index++] = new SqlParameter("@param7", grantAmtFrom);
                        param[index++] = new SqlParameter("@param8", grantAmtTo);
                    }
                }
            }
        }
    }
}
